﻿namespace FallingRocks
{
    using System.Collections.Generic;
    using System.Linq;

    public static class CollisionDetector
    {
        public static bool CheckForCollisions(List<IRenderable> movingObjects, GameObject player, int eligibleCollisionRegion = 1)
        {            
            IEnumerable<IRenderable> objectsToCheck = movingObjects.Where(x => x.Position.Y == (player.Position.Y - eligibleCollisionRegion));

            foreach (GameObject movingObject in objectsToCheck)
            {
                int upperX = movingObject.Position.X;
                int lowerX = player.Position.X + 1;

                for (int upper = upperX; upper < upperX + movingObject.Visualisation.Length; upper++)
                {
                    for (int lower = lowerX; lower < lowerX + player.Visualisation.Length - 1; lower++)
                    {
                        if (upper == lower && player.CanCollideWith(movingObject))
                        {
                            return player.RespondToCollision(movingObject);
                        }
                    }
                }
            }

            return false;
        }
    }
}
